package timing.ukulele.auth.security.type.sms;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.SecurityContextRepository;
import timing.ukulele.auth.security.handler.LoginFailureHandler;
import timing.ukulele.auth.security.handler.LoginSuccessHandler;
import timing.ukulele.auth.security.user.TimingUserDetailService;
import timing.ukulele.auth.support.RedisOperator;

public class SmsCodeAuthenticationSecurityConfig implements SecurityConfigurer<DefaultSecurityFilterChain, HttpSecurity> {

    private final LoginFailureHandler loginFailHandler;
    private final LoginSuccessHandler loginSuccessHandler;
    private final TimingUserDetailService userService;
    private final RedisOperator<String> stringRedisOperator;

    public SmsCodeAuthenticationSecurityConfig(
            LoginFailureHandler loginFailHandler,
            LoginSuccessHandler loginSuccessHandler,
            TimingUserDetailService userService,
            RedisOperator<String> stringRedisOperator) {
        this.loginFailHandler = loginFailHandler;
        this.loginSuccessHandler = loginSuccessHandler;
        this.userService = userService;
        this.stringRedisOperator = stringRedisOperator;
    }


    @Override
    public void init(HttpSecurity http) {

    }

    @Override
    public void configure(HttpSecurity http) {
        SmsCodeAuthenticationFilter authenticationFilter = new SmsCodeAuthenticationFilter(stringRedisOperator);
        authenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        authenticationFilter.setAuthenticationSuccessHandler(loginSuccessHandler);
        authenticationFilter.setAuthenticationFailureHandler(loginFailHandler);

        SmsCodeAuthenticationProvider authenticationProvider = new SmsCodeAuthenticationProvider();
        authenticationProvider.setUserService(userService);

        http.authenticationProvider(authenticationProvider)
                .addFilterAt(authenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}